import { defineStore } from 'pinia'
import { api } from '@/api'

export const useAuthStore = defineStore('auth', {
    state: () => ({ token: localStorage.getItem('token') || '', user: null }),
    getters: { isAuthed: s => !!s.token },
    actions: {
        async register(email, password, username) {
            console.log('[AUTH] register ->', { email, username })
            await api.post('/auth/register', { email, password, username })
            console.log('[AUTH] register ok')
        },
        async login(account, password) {
            console.log('[AUTH] login ->', { account })
            const res = await api.post('/auth/login', { email: account, password })
            console.log('[AUTH] login resp =', res) // 期望 { token: '...' }
            const tok = res?.token || ''
            if (!tok) { throw new Error('后端未返回 token') }
            this.token = tok
            localStorage.setItem('token', tok)
            console.log('[AUTH] token saved, store=', this.token.slice(0,12)+'...', 'ls=', (localStorage.getItem('token')||'').slice(0,12)+'...')
            try {
                await this.fetchMe()
            } catch (e) {
                console.warn('[AUTH] fetchMe after login failed', e?.response?.status, e?.response?.data)
            }
        },
        async fetchMe() {
            console.log('[AUTH] fetchMe -> using token=', this.token ? this.token.slice(0,12)+'...' : '(none)')
            const me = await api.get('/user/me')
            console.log('[AUTH] fetchMe ok =', me)
            this.user = me
            return me
        },
        logout() {
            console.log('[AUTH] logout')
            this.token = ''
            this.user = null
            localStorage.removeItem('token')
        }
    }
})
